package cn.wgoodq.study.MultiThreading.exercise.entity;

import java.util.Arrays;

/**
 * Created by OuKyou on 2017/1/21.
 */
public class Parkinglot {

    // 所有车位
    private String[] cheWeis = new String[]{"", "", ""};

    synchronized void cunChe(String name) throws InterruptedException {

        System.out.println(name + " 准备存车，车库：" + Arrays.toString(cheWeis));
        if (isFull()) {
            // 车位满了进行等待；
            System.out.println("车位已满！-- {" + name + "}进入等待。");
            wait();
        }

        if (doCunChe(name)) {
            System.out.println(name + " 存车成功，结果：" + Arrays.toString(cheWeis));
        }
        notify();

    }

    synchronized boolean quChe(String name) throws InterruptedException {
        System.out.println(name + " 准备取车，车库：" + Arrays.toString(cheWeis));
        for (int i = 0; i < cheWeis.length; i++) {
            if (!cheWeis[i].isEmpty()) {
                cheWeis[i] = "";
                System.out.println(name + " 取车成功!");
                notify();
                return true;
            }
        }
        System.out.println(name + " 取车失败，进入等待！");

        wait();
        return false;
    }

    private boolean isFull() {
        for (String chewei : cheWeis) {
            if (!chewei.isEmpty()) {
                continue;
            }
            return false;
        }
        return true;
    }

    private boolean doCunChe(String name) {
        for (int i = 0; i < cheWeis.length; i++) {
            if (cheWeis[i].isEmpty()) {
                cheWeis[i] = name;
                return true;
            }
        }
        System.err.println(name + ": 说好的车位没了！！！！！！！！！！！！！！！！");
        return false;
    }

}
